package com.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.config.MyAliPayConfig;
import com.config.RequestAliPay;
import com.entity.HyOrder;
import com.entity.HyPayment;
import com.service.IAliPayService;
import com.service.OrderService;
import com.service.PaymentService;
import com.utils.R;
import com.utils.ZhifubaoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @program: honye-fang
 * @description:
 * @author: Baiyyy
 * @create: 2025-02-14 22:04
 **/
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService; // 注入订单服务

    @Autowired
    private IAliPayService aliPayService;

    @PostMapping()
    public R aliPay(@RequestBody RequestAliPay requestAliPay) throws AlipayApiException {
        //下单
        return R.ok();
    }

    //发起支付请求
    @PostMapping("/pay/{orderId}")
    public R pay(@PathVariable Long orderId) throws AlipayApiException {
        //获取订单信息
        HyOrder orderByUserId = orderService.getOrderById(orderId);
         if (orderByUserId == null){
             return R.error("订单不存在");
         }


         //创建支付记录
        HyPayment hyPayment = new HyPayment();
        hyPayment.setOrderId(orderId);
        // 支付金额 = 单价 * 数量
        hyPayment.setAmount(orderByUserId.getPrice());
        hyPayment.setPaymentStatus("未支付");
        hyPayment.setPaymentMethod("支付宝"); // 使用支付宝
        int result = paymentService.insertPayment(hyPayment);

        if (result <= 0) {
            return R.error("支付订单创建失败");
        }

        //获得初始化的AlipayClient
        MyAliPayConfig myAliPayConfig = new MyAliPayConfig();
        AlipayClient alipayClient = new DefaultAlipayClient(myAliPayConfig.getServerUrl(),
                myAliPayConfig.getAppId(),
                myAliPayConfig.getPrivateKey(),
                myAliPayConfig.getFormat(),
                myAliPayConfig.getCharset(),
                myAliPayConfig.getAlipayPublicKey(),
                myAliPayConfig.getSignType());
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(myAliPayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(myAliPayConfig.getNotifyUrl());

      // 这里是调用支付平台接口
        RequestAliPay requestAliPay = RequestAliPay.builder()
                .outTradeNo("1253435614316")
                .authNo("12354325125")
                .totalAmount(hyPayment.getAmount())
                .subject("我的订单").productCode("111111").build();

        // 前端跳转到该支付链接即可完成支付
        return R.ok(aliPayService.aliPay(requestAliPay));
    }


    //添加支付信息
    @PostMapping("/addPayment")
    public R createPayment(@RequestBody HyPayment hyPayment) {
        Integer result = paymentService.insertPayment(hyPayment);  // 调用服务层插入支付信息
        if (result > 0) {
            return R.ok("支付信息插入成功");  // 返回成功响应
        } else {
            return R.error("支付信息插入失败");  // 返回失败响应
        }
    }

    //根据支付ID查询支付信息
    @GetMapping("/getPaymentById/{id}")
    public R getPaymentById(@PathVariable Long id) {
        HyPayment hyPayment = paymentService.selectPaymentById(id);  // 调用服务层查询支付信息
        if (hyPayment != null) {
            return R.ok().put("payment", hyPayment);  // 返回成功响应，并携带支付信息
        } else {
            return R.error("支付信息查询失败");  // 返回失败响应
        }
    }


    //更新支付状态
    @PutMapping("/updatePaymentStatus/{id}/{paymentStatus}")
    public R updatePaymentStatus(@PathVariable Long id, @PathVariable String paymentStatus) {
        Integer result = paymentService.updatePaymentStatus(id, paymentStatus);  // 调用服务层更新支付状态
        if (result > 0) {
            return R.ok("支付状态更新成功");  // 返回成功响应
        } else {
            return R.error("支付状态更新失败");  // 返回失败响应
        }
    }

}
